<?php

namespace app\web\service;

use app\common\logic\AirportLogic;
use app\common\logic\OrderLogic;
use app\common\logic\PayLogic;
use app\common\model\commonModel;
use app\common\model\trAirport;
use app\common\model\trAirportLine;
use app\common\model\trCache;
use app\common\model\trCarType;
use app\common\model\trOrder;
use app\common\model\trResource;
use app\common\model\trUser;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use app\common\util\WxPay;

/**
 * Class Auth
 * @package app\web\service
 * 机场服务类
 */
class AirportService
{
    private $params;
    private $returnData;

    public function __construct($data, $params)
    {
        $this->returnData = $data;
        $this->params = $params;
    }

    // 获取下订单页的数据
    public function getOrderData(){
        if (empty($this->params['type'])) {
            return ErrorCode::code("params_not_exist", "type");
        }
        if (!in_array($this->params['type'], [1,2])) { // 1接机，2送机
            return ErrorCode::code("params_error", "type（1接机，2送机）");
        }
        $model = new trAirportLine();
        if($this->params['type'] == "1"){
            $data = $model->getBasic_1_CacheData();
        }else if($this->params['type'] == "2"){
            $data = $model->getBasic_2_CacheData();
        }
        $airportData = [];
        if(!empty($data)) {
            $airportModel = new trAirport();
            foreach ($data as $id => $airportId) {
                if(empty($airport[$airportId])) {
                    $airport[$airportId] = $airportModel->getFields("name,placards,price,status", ["id" => $airportId]);
                }
                if(!empty($airport[$airportId]) && $airport[$airportId]["status"] == "1") {
                    if(empty($airportData[$airportId])) {
                        $airportData[$airportId] = [
                            "id" => $airportId,
                            "name" => $airport[$airportId]["name"],
                            "placards" => $airport[$airportId]["placards"],
                            "price" => $airport[$airportId]["price"],
                            "lineId" => $id,
                        ];
                    }else{
                        $airportData[$airportId]["lineId"] = $airportData[$airportId]["lineId"] . ",{$id}";
                    }
                }
            }
        }
        $this->returnData["data"] = ["airport" => array_values($airportData), "remark" => AirportLogic::getLineRemark()];
        return $this->returnData;
    }

    public function getOrderSure($userId){
        if (empty($this->params['lineId'])) {
            return ErrorCode::code("params_not_exist", "lineId");
        }
        if (empty($this->params['chooseTime'])) {
            return ErrorCode::code("params_not_exist", "选择时间");
        }
        if (!empty($this->params['latitude']) && !empty($this->params["longitude"])) {
            $res = AirportLogic::getDetailAddress($this->params["latitude"], $this->params["longitude"]);
            if(isset($res["code"])){
                return $res;
            }
            $this->params['address'] = $res;
        }else if (empty($this->params['address'])) {
            return ErrorCode::code("params_not_exist", "记得选择上下车地点哦~");
        }
        if(strpos($this->params["lineId"], ",") !== false){
            $this->params["lineId"] = explode(",", $this->params["lineId"]);
        }else{
            $this->params["lineId"] = [$this->params["lineId"]];
        }
        $chooseId = [];
        $model = new trAirportLine();
        $carTypeModel = new trCarType();
        foreach ($this->params["lineId"] as $lineId){
            if($redisObject = redis_object() !== false) {
                $lineData = $model->getFields("id,open_default,open_weekend,open_date,date_between,default_price,weekend_price,date_price", ["id" => $lineId], true, false);
                $lineData = array_merge($lineData, $model->getPCACacheData($lineId));
            }else{
                $lineData = $model->getFields(
                    "id,province_code,city_code,area_code,car_type,charge_type,open_default,open_weekend,open_date,date_between,default_price,weekend_price,date_price",
                    ["id" => $lineId], true, false
                );
            }
            if(empty($lineData)){
                continue;
            }
            $pcaText = Tools::getNameByPCA($lineData["provinceCode"], $lineData["cityCode"], $lineData["areaCode"]);
            $text = str_replace(" ", "", $pcaText);
            if(strpos($this->params["address"], $text) !== false){
                if(!empty($lineData) && ($type = AirportLogic::getJudgeOpenType($lineData, $this->params["chooseTime"]))) { //$type = ; // 1：日期；2：周末；3：默认
                    if(empty($typeName[$lineData["carType"]])) {
                        $typeName[$lineData["carType"]] = $carTypeModel->getFields("name,seat,icon,remark", ["id" => $lineData["carType"]]);
                    }
                    $cacheKey = Tools::createGUID();
                    $lineData["address"] = $pcaText . " " . substr($this->params["address"], strlen($text));
                    $lineData["rideNumber"] = $typeName[$lineData["carType"]]["seat"];
                    $lineData["latitude"] = isset($this->params["latitude"]) ? $this->params["latitude"] : 0;
                    $lineData["longitude"] = isset($this->params["longitude"]) ? $this->params["longitude"] : 0;
                    trCache::saveCache(["key" => $cacheKey . $userId, "value" => $lineData, "time" => 600]);
                    $chooseId[] = [
                        "lineId" => $lineId, "rideNumber" => $lineData["rideNumber"], "money" => AirportLogic::getShowPrice($lineData, $type), "orderKey" => $cacheKey,
                        "carTypeName" => $typeName[$lineData["carType"]]["name"], "carTypeRemark" => $typeName[$lineData["carType"]]["remark"],
                        "carTypeIcon" => tome_dia(trResource::getValue("url", ["id" => $typeName[$lineData["carType"]]["icon"]])),
                        "chargeType" => $lineData["chargeType"]
                    ];
                }
            }
        }
        if(empty($chooseId)){
            return ErrorCode::code("customized", "该区域未开通");
        }
        $this->returnData["data"] = $chooseId;
        return $this->returnData;
    }

    // 提交订单
    public function toSubmitOrder($userId, $openid){
        $field = [
            "orderKey" => "orderKey", "chooseTime" => "选择日期", "shiftTime" => "选择时间", "contactId" => "联系人",
            "placards" => "举牌支持", "rideNumber" => "乘车人数"
        ];
        foreach ($field as $k => $v) {
            if(!isset($this->params[$k])){
                $this->returnData = ErrorCode::code('params_not_exist', $v);
                return $this->returnData;
            }
        }
        $cacheData = trCache::getValue("value", ["key" => $this->params["orderKey"] . $userId]);
        if(empty($cacheData)){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "订单已创建";
            return $this->returnData;
        }
        if(!is_numeric($this->params["rideNumber"])){
            return ErrorCode::code("params_format", "乘车人数");
        }
        if($cacheData["rideNumber"] < $this->params["rideNumber"]){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "乘车人数超过座位量";
            return $this->returnData;
        }
        $this->params["rideNumber"] = intval($this->params["rideNumber"]);
        if(!($type = AirportLogic::getJudgeOpenType($cacheData, $this->params['chooseTime']))){
            return ErrorCode::code("customized", "该{$this->params['chooseTime']}时间没有开通");
        }
        $contactData = commonModel::getFields(contactTable, "prefix,mobile,name", ["id" => $this->params["contactId"], "user_id" => $userId], true, false);
        if(empty($contactData)){
            return ErrorCode::code("params_error", "contactId（联系人ID）");
        }
        // 计算总价、计算佣金
        $model = new trAirportLine();
        $data = $model->getFields("airport,type,default_commission,weekend_commission,date_commission", ["id" => $cacheData["id"]], true, false);
        if($data["type"] == "1"){// 1接机
            if(empty($this->params["flightNumber"])){
                $this->returnData = ErrorCode::code('params_not_exist', "航班号");
                return $this->returnData;
            }
        }
        if($cacheData["chargeType"] == "0"){ // 按人头
            $totalMoney = AirportLogic::getShowPrice($cacheData, $type) * $this->params["rideNumber"];
        }else{ // 按车辆
            $totalMoney = AirportLogic::getShowPrice($cacheData, $type);
        }
        $commission = AirportLogic::getShowCommission($data, $type);
        $airportModel = new trAirport();
        $airportData = $airportModel->getFields("name,placards,price", ["id" => $data["airport"]]);
        if($this->params["placards"] == "2" && $airportData["placards"] == "2"){
            $totalMoney += $airportData["price"];
        }
        if(empty($totalMoney)){
            return ErrorCode::code("customized", "价格有误");
        }
        $couponAmount = 0;      // 优惠金额
        $userCouponId = 0;     //优惠券id
        if(!empty($this->params['userCouponId']) && !empty($couponInfo = commonModel::getFields(userCouponTable,'amount',['id' => $this->params['userCouponId']]))){
            $userCouponId = $this->params['userCouponId'];
            $couponAmount = $couponInfo['amount'];
        }elseif(!empty($this->params["coupon"]) && !empty($couponInfo = commonModel::getFields(userCouponTable,'id,amount',["coupon_id" => $this->params["coupon"], "user_id" => $userId]))){
            $userCouponId = $couponInfo["id"];
            $couponAmount = $couponInfo['amount'];
        }
        $orderModel = new trOrder();
        $orderSn = $orderModel->getSn();
        $paymentNo = $orderModel->getPayNo();
        $orderData = [
            "order_sn" => $orderSn,
            "mall_id" => request()->mallData["id"],
            "line_id" => $cacheData["id"],
            "user_id" => $userId,
            "contact_name" => $contactData["name"],
            "mobile" => $contactData["prefix"].$contactData["mobile"],
            "ride_number" => $this->params["rideNumber"],   // 总票数
            "total_money" => $totalMoney,  // 订单总价格
            "pay_money" => $totalMoney > $couponAmount ? $totalMoney - $couponAmount : 0,  // 去支付的价格
            "discount_money" => $couponAmount, // 没接优惠券，所有默认0
            "commission" => $commission,
            "coupon_id" => $userCouponId,    //新 用户优惠券表 id
            "reserve_time" => $this->params["chooseTime"] . " " . $this->params["shiftTime"], // 预约时间，出发时间
            "type" => 1,   //类型；1机场接送，2固定路线，3专车接送
            "payment_no" => $paymentNo,
            "memo" => isset($this->params["memo"]) ? $this->params["memo"] : "",
            "flight_number" => $this->params["flightNumber"],
        ];
        if($data["type"] == "1"){// 1接机，
            $orderData["address_from"] = $airportData["name"];
            if (!empty($cacheData["address"])) {
                $orderData["address_to"] = $cacheData["address"];
            }else{
                $orderData["address_to"] = Tools::getNameByPCA($cacheData["provinceCode"], $cacheData["cityCode"], $cacheData["areaCode"]);
            }
            $orderData["long_lat_to"] = $cacheData["longitude"]. ",".$cacheData["latitude"];
            $orderSn = $orderData["order_sn"] = "1".$orderData["order_sn"];
        }else if($data["type"] == "2"){ // 2送机
            if (!empty($cacheData["address"])) {
                $orderData["address_from"] = $cacheData["address"];
            }else{
                $orderData["address_from"] = Tools::getNameByPCA($cacheData["provinceCode"], $cacheData["cityCode"], $cacheData["areaCode"]);
            }
            $orderData["long_lat_from"] = $cacheData["longitude"]. ",".$cacheData["latitude"];
            $orderData["address_to"] = $airportData["name"];
            $orderSn = $orderData["order_sn"] = "2".$orderData["order_sn"];
        }
        if($orderId = $orderModel->add($orderData, true)){
            if(!empty($this->params["formId"]) && strpos($this->params["formId"], "the formId") === false){ // 存 form_id
                commonModel::toAdd(formIdTable, [
                    "user_id" => $userId, "form_id" => $this->params["formId"], "type" => "prepay_id", "create_time" => time(), "mall_id" => request()->mallData["id"]
                ]);
            }
            trCache::del($this->params["orderKey"] . $userId);
            //订单后续操作
            if($orderData["pay_money"]) {
                $data = ["total_fee" => $orderData["pay_money"] * 100, "openid" => $openid, "out_trade_no" => $paymentNo, "body" => "机场接送支付"];
                // 加的测试
                if (in_array(request()->host(), ["cardemo.wegouer.com/test/cars-pai", "service-emhatyrq-1251017581.gz.apigw.tencentcs.com/test/cars-pai"])) {
                    $data["total_fee"] = 1; // 测试 1毛
                }
                $wxPay = new WxPay();
                $res = $wxPay->toPay($data); // 获取支付信息
                if (isset($res["code"])) {
                    $this->returnData = $res;
                } else {
                    // 订单有效时间为30分钟，时间一到就要自动取消
                    OrderLogic::cancelOrderJobs($orderSn, ["orderSn" => $orderSn, "userId" => $userId]);
                    $res["orderSn"] = $orderSn;
                    $this->returnData["data"] = $res;
                }
            }else{
                $payLogic = new PayLogic();
                $userModel = new trUser();
                $payLogic->updateOrder($paymentNo, ["tradeNo" => "", "totalFee" => 0, "payAccount" => $userModel->getValue("nickname", ["id" => $userId])]);
                $this->returnData["data"] = ["orderSn" => $orderSn];
            }
        }else{
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "生成订单失败";
        }
        return $this->returnData;
    }
}